package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.mapper.InventoryAdjustRecordMapper;
import com.zhentao.mapper.InventoryMapper;
import com.zhentao.pojo.Inventory;
import com.zhentao.pojo.InventoryAdjustRecord;
import com.zhentao.service.InventoryAdjustService;
import com.zhentao.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class InventoryAdjustServiceImpl extends ServiceImpl<InventoryAdjustRecordMapper, InventoryAdjustRecord>
        implements InventoryAdjustService {

    @Autowired
    private InventoryMapper inventoryMapper;

    @Override
    public Result adjust(Integer inventoryId, Integer newStock, String remark, Integer operatorId) {
        Inventory inventory = inventoryMapper.selectById(inventoryId);
        if (inventory == null) {
            return Result.ERROR("库存记录不存在");
        }
        Integer before = inventory.getCurrentStock();
        inventory.setCurrentStock(newStock);
        inventory.setDate(new Date());
        inventoryMapper.updateById(inventory);

        InventoryAdjustRecord record = new InventoryAdjustRecord();
        record.setInventoryId(inventoryId);
        record.setDishId(inventory.getDishId());
        record.setBeforeStock(before);
        record.setAfterStock(newStock);
        record.setChangeAmount(newStock - (before == null ? 0 : before));
        record.setRemark(remark);
        record.setOperatorId(operatorId);
        record.setOperateTime(new Date());
        this.save(record);

        return Result.OK();
    }

    @Override
    public Result listByDish(Integer dishId, Integer pageNum, Integer pageSize) {
        Page<InventoryAdjustRecord> page = new Page<>(pageNum, pageSize);
        QueryWrapper<InventoryAdjustRecord> qw = new QueryWrapper<>();
        qw.eq(dishId != null, "dish_id", dishId).orderByDesc("operate_time");
        this.page(page, qw);
        return Result.OK(page);
    }
}


